import React, { memo } from 'react';
import { useDerivedValue } from 'react-native-reanimated';
import { useAdaptiveSheetInternal } from '../../hooks';
import { KEYBOARD_STATE } from '../../constants';
import type { AdaptiveSheetFooterContainerProps } from './types';

const AdaptiveSheetFooterContainerComponent = ({ footerComponent: FooterComponent }: AdaptiveSheetFooterContainerProps): JSX.Element | null => {
  const { animatedContainerHeight, animatedHandleHeight, animatedFooterHeight, animatedPosition, animatedKeyboardState, animatedKeyboardHeightInContainer } =
    useAdaptiveSheetInternal();

  const animatedFooterPosition = useDerivedValue(() => {
    const keyboardHeight = animatedKeyboardHeightInContainer.value;
    let footerTranslateY = Math.max(0, animatedContainerHeight.value - animatedPosition.value);

    if (animatedKeyboardState.value === KEYBOARD_STATE.SHOWN) {
      footerTranslateY = footerTranslateY - keyboardHeight;
    }

    footerTranslateY = footerTranslateY - animatedFooterHeight.value - animatedHandleHeight.value;

    return footerTranslateY;
  }, [animatedKeyboardHeightInContainer, animatedContainerHeight, animatedPosition, animatedKeyboardState, animatedFooterHeight, animatedHandleHeight]);

  return <FooterComponent animatedFooterPosition={animatedFooterPosition} />;
};

const AdaptiveSheetFooterContainer = memo(AdaptiveSheetFooterContainerComponent);
AdaptiveSheetFooterContainer.displayName = 'AdaptiveSheetFooterContainer';

export default AdaptiveSheetFooterContainer;
